﻿using System;
using System.Collections.Generic;
using LxBasic;
using LxCore;

namespace LxCore
{
    public class MonitorBase : JsIdentifyItem
    {
        private double _DefaultValue = 0;
        public double DefaultValue
        {
            get { return _DefaultValue; }
            set { _DefaultValue = value; RaisePropertyChanged(nameof(DefaultValue)); }
        }
        private double _LatestValue = 0;
        public double LatestValue
        {
            get { return _LatestValue; }
            set { _LatestValue = value; RaisePropertyChanged(nameof(LatestValue)); }
        }
        private bool _IsLatestValueValid = false;
        public bool IsLatestValueValid
        {
            get { return _IsLatestValueValid; }
            set { _IsLatestValueValid = value; RaisePropertyChanged(nameof(IsLatestValueValid)); }
        }
        public double GetValue()
        {
            return IsLatestValueValid ? LatestValue : DefaultValue;
        }

        public List<Vector2d>? HistoryData;
        public virtual void RunStatistic()
        {
        }
        public void AddHistoryData(double x, double y)
        {
            if (HistoryData == null)
            {
                HistoryData = new();
            }
            HistoryData.Add(new Vector2d(x, y));
        }
        public virtual void ClearHistory()
        {
            IsLatestValueValid = false;
            LatestValue = 0;
            HistoryData?.Clear();
        }
        public override void FromJsonKV(string key, IJsonReader jsReader)
        {
            switch (key)
            {
                case nameof(DefaultValue):DefaultValue =jsReader.ReadDouble(); break;
                case nameof(LatestValue):LatestValue =jsReader.ReadDouble(); break;
                case nameof(IsLatestValueValid):IsLatestValueValid = jsReader.ReadBool();break;
                case nameof(HistoryData):
                    Vector2d[] his = null;
                    jsReader.ReadVector2dArray(his,e=>his=e);
                    HistoryData = new List<Vector2d>(his);
                    break;
                default: base.FromJsonKV(key, jsReader); break;
            }
        }
        public override void ToJsonKV(IJsonWriter jsWriter)
        {
            base.ToJsonKV(jsWriter);
            //jsWriter.WriteDouble(nameof(DefaultValue), DefaultValue);
            jsWriter.WriteDouble(nameof(LatestValue), LatestValue);
            jsWriter.WriteBool(nameof(IsLatestValueValid), IsLatestValueValid);
            if (HistoryData != null)
            {
                jsWriter.WriteVector2dArray(nameof(HistoryData), HistoryData.ToArray());
            }
        }
    }
}